package com.example.employeemanagement.service.impl;

import com.example.employeemanagement.entry.Department;
import com.example.employeemanagement.mapper.DepartmentMapper;
import com.example.employeemanagement.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 部门服务实现类
 * 实现部门管理的业务逻辑
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> getAllDepartments() {
        return departmentMapper.getAllDepartments();
    }

    @Override
    public Optional<Department> getDepartmentById(Integer departmentId) {
        Department department = departmentMapper.getDepartmentById(departmentId);
        return Optional.ofNullable(department);
    }

    @Override
    @Transactional
    public String addDepartment(Department department) {
        try {
            int result = departmentMapper.addDepartment(department);
            if (result > 0) {
                return "部门添加成功，ID: " + department.getDepartment_id();
            } else {
                return "部门添加失败";
            }
        } catch (Exception e) {
            return "部门添加失败: " + e.getMessage();
        }
    }

    @Override
    @Transactional
    public String updateDepartment(Integer departmentId, Department department) {
        try {
            // 检查部门是否存在
            boolean exists = departmentMapper.existsById(departmentId);
            if (!exists) {
                return "更新失败：部门ID " + departmentId + " 不存在";
            }
            
            // 设置ID确保更新正确的记录
            department.setDepartment_id(departmentId);
            
            int result = departmentMapper.updateDepartment(department);
            if (result > 0) {
                return "部门更新成功";
            } else {
                return "部门更新失败";
            }
        } catch (Exception e) {
            return "部门更新失败: " + e.getMessage();
        }
    }

    @Override
    @Transactional
    public String deleteDepartment(Integer departmentId) {
        try {
            // 检查部门是否存在
            boolean exists = departmentMapper.existsById(departmentId);
            if (!exists) {
                return "删除失败：部门ID " + departmentId + " 不存在";
            }
            
            // 这里可以添加检查是否有员工关联到此部门的逻辑
            // 如果有关联，可以返回错误信息或者级联删除
            
            int result = departmentMapper.deleteDepartment(departmentId);
            if (result > 0) {
                return "部门删除成功";
            } else {
                return "部门删除失败";
            }
        } catch (Exception e) {
            return "部门删除失败: " + e.getMessage();
        }
    }
}